#!/usr/bin/env node

/**
 * 测试用：关联用户到admin账号
 * 用于解决测试环境中的权限问题
 */

const AdminModel = require('./model/admin_model.js');
const timeUtil = require('../framework/utils/time_util.js');

async function linkUserToAdmin(userId, adminId = 'admin_001') {
    try {
        console.log('=== 关联用户到admin账号 ===');
        console.log('用户ID:', userId);
        console.log('Admin ID:', adminId);
        
        // 检查admin账号是否存在
        const admin = await AdminModel.getOne({
            ADMIN_ID: adminId,
            ADMIN_STATUS: 1
        });

        if (!admin) {
            console.log('❌ Admin账号不存在，正在创建...');
            
            // 创建admin账号
            const adminData = {
                ADMIN_ID: adminId,
                ADMIN_NAME: 'admin',
                ADMIN_PHONE: '13900000000',
                ADMIN_STATUS: 1,
                ADMIN_TYPE: 1,
                ADMIN_LOGIN_CNT: 0,
                ADMIN_LOGIN_TIME: 0,
                ADMIN_TOKEN: '',
                ADMIN_TOKEN_TIME: 0,
                ADMIN_ADD_TIME: timeUtil.time(),
                ADMIN_EDIT_TIME: timeUtil.time(),
                
                linkedUserId: userId,
                linkedStoreIds: [],
                permissions: {
                    device_management: true,
                    store_management: true,
                    user_management: true,
                    order_management: true,
                    payment_management: true,
                    statistics: true,
                    system_settings: true
                },
                lastLoginDevice: '',
                isActive: true,
                role: 'super_admin',
                description: '超级管理员账号'
            };
            
            const result = await AdminModel.insert(adminData);
            console.log('✅ Admin账号创建成功:', result.id);
        } else {
            console.log('✅ Admin账号已存在:', admin.ADMIN_ID);
            
            // 更新关联信息
            const updateData = {
                linkedUserId: userId,
                linkedStoreIds: admin.linkedStoreIds || [],
                permissions: admin.permissions || {
                    device_management: true,
                    store_management: true,
                    user_management: true,
                    order_management: true,
                    payment_management: true,
                    statistics: true,
                    system_settings: true
                },
                ADMIN_EDIT_TIME: timeUtil.time()
            };

            await AdminModel.edit({
                ADMIN_ID: adminId
            }, updateData);
            
            console.log('✅ 用户关联更新成功');
        }
        
        console.log('=== 关联完成 ===');
        
        return {
            success: true,
            message: '用户关联成功',
            userId: userId,
            adminId: adminId
        };
        
    } catch (error) {
        console.error('❌ 关联用户失败:', error);
        return {
            success: false,
            message: '关联失败: ' + error.message
        };
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    const userId = process.argv[2] || 'oPOlNvkKFRjdTazLzUq6D2sHunp0'; // 默认使用日志中的用户ID
    const adminId = process.argv[3] || 'admin_001';
    
    linkUserToAdmin(userId, adminId).then(result => {
        console.log('最终结果:', result);
        process.exit(result.success ? 0 : 1);
    }).catch(error => {
        console.error('脚本执行失败:', error);
        process.exit(1);
    });
}

module.exports = { linkUserToAdmin };
